<?php

namespace Utuo;

class Upload {
	
	
	protected $error = "";
	
	protected $config = null;
	
	public function __construct( $config ) {
	    $defaultConfigs = array(
	        'maxSize' => C('UPLOAD_MAX_SIZE'),
	        'exts' => C('UPLOAD_IMG_EXTS'),
	        'rootPath' => '/Uploads',
	        'saveName' => date('YmdHis') . rand(1234, 9999) . rand(1234, 9999),
	    );
	    $config and $defaultConfigs = array_merge($defaultConfigs, $config);
	    $this->config = $defaultConfigs;
	}
	
	/**
	 * 上传单个文件
	 * @param string $configs
	 * @return array boolean
	 */
	public function uploadOne($configs = null) {
		$info = $this->start($configs);
		$info = $info ? $info['Filedata'] : $info;
		if ($info) {
			$result = array();
			$result[] = &$info;
			$this->bindUrl($result);
		}
		return $info;
	}
	
	public function uploadSome($configs = null) {
		$info = $this->start($configs);
		$this->bindUrl($info); 
		return $info;
	}
	
	public function bindUrl(&$info) {
		if(APP_MODE == 'sae'){
			$storage = new \SaeStorage();
		}
		foreach ($info as &$v) {
			if(APP_MODE == 'sae'){
				$v['url'] = $storage->getUrl(C('UPLOAD_DOMAIN'), $v['savepath'] . $v['savename']);
				$v['saestorPath'] = "saestor://".C('UPLOAD_DOMAIN').'/'.$v['savepath'] . $v['savename'];
			}else{
				$v['url'] = $this->config['rootPath']."/".$v['savepath'] . $v['savename'];
				$v['saestorPath'] = $this->config['rootPath']."/".$v['savepath'] . $v['savename'];
			}
		}
	}
	
	public function start($configs) {
		$driveConfigs = array(
			'domain' => C('UPLOAD_DOMAIN'),
			'rootPath'=>'Uploads'
		);
		is_null($configs) and $configs = array();
		$configs = array_merge($this->config, $configs);
//		$upload = new \Think\Upload($configs, null, $driveConfigs);
		$upload = new \Think\Upload();
		$info = $upload->upload($_FILES);
		$this->error = $upload->getError();
		return $info;
	}
	
	// 获得错误信息
	public function getError() {
		return $this->error;
	}
}